<?php

namespace App\Common\Libs\Dispatch;

use App\Common\Libs\Json;
use App\Consts\GlobalQueueConst;
use App\Jobs\BaseJob;

/**
 * Class Queue
 * @package App\Common\Libs\Dispatch
 */
class Queue
{

    /** @var $instance */
    public static $instance;

    /**
     * @var BaseJob $client
     */
    public $client;

    /**
     * Queue constructor.
     * @param $class
     */
    public function __construct($class)
    {
        if (new $class instanceof BaseJob) {
            $this->client = new $class;
        }
    }

    /**
     * Get instance
     *
     * @param string $class
     * @return Queue
     */
    public static function getInstance(string $class)
    {
        if (isset(self::$instance[$class])) {
            return self::$instance[$class];
        }
        return self::$instance[$class]  = new self($class);
    }

    /**
     * Push data to job
     *
     * @param $data
     * @param $scene
     * @param string $driver
     * @param int $delay
     * @return \Illuminate\Foundation\Bus\PendingDispatch
     */
    public function push($data, $scene, $driver = GlobalQueueConst::DRIVER_TYPE_QUEUE, $delay = 0)
    {
        $body = ['action' => $scene, 'json' => Json::encode($data)];
        return $this->client::dispatch($body, $driver, $delay);
    }

    /**
     * Batch push data to job
     *
     * @param $list
     * @param $scene
     * @return \Illuminate\Bus\Batch|int
     */
    public function batch($list, $scene)
    {
        $batch = [];
        foreach ($list as $item) {
            $batch[] = ['action' => $scene, 'json' => Json::encode($item)];
        }
        return $this->client::dispatchAll($batch);
    }

}
